using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Xml.Serialization;
using System.Xml;
using System.Diagnostics;

namespace Axe.Configuration
{
    public class ConfigurationFileMapping<T> where T:IConfiguration 
    {
        Type m_ConfigType;
        XmlSerializer m_Serializer;

        public ConfigurationFileMapping()
        {
            m_ConfigType = typeof(T);
            m_Serializer = new XmlSerializer(m_ConfigType);
        }

        public T Load(string filename,bool setDefaultOnError)
        {
            T cfg = default(T);

            if (TryLoad(filename, out cfg) == false && setDefaultOnError)
            {
                cfg = Activator.CreateInstance<T>();
                cfg.SetDefault();

                Save(filename, cfg);
            }

            return cfg;
        }

        public bool TryLoad (string fileName, out T config)
        {
            config = default(T);

            if(File.Exists(fileName) == false)
            {
                return false;
            }

            FileStream fs = null;

            try
            {
                using(fs = new FileStream(fileName,FileMode.Open))
                {
                    using (XmlTextReader xmlReader = new XmlTextReader(fs))
                    {
                        if (m_Serializer.CanDeserialize(xmlReader))
                        {
                            config = (T)m_Serializer.Deserialize(xmlReader);
                            return true;
                        }
                        else
                        {
                            return false;
                        }
                    }
                }

            }
            catch(Exception e)
            {
                Debug.WriteLine(e.Message);
                return false;
            }
        }

        public bool Save(string fileName, T config)
        {
            try
            {
                using (FileStream fs = new FileStream(fileName, FileMode.Create))
                {
                    m_Serializer.Serialize(fs, config);
                }

                return true;
            }
            catch(Exception e)
            {
                Debug.WriteLine(e.Message);
                return false;
            }
        }
    }
}
